import 'package:dio/dio.dart';
import 'package:get/get.dart';
import 'base_service.dart';

/// 录像管理服务类 - GetX服务
class RecordService extends GetxService {
  final BaseService _baseService = BaseService();

  /// 2.8.1 开始录像
  ///
  /// [streamId] 实时/回放流ID (必填)
  /// [interval] 录像分段周期(秒)，默认为0表示录像不分段
  ///
  /// 返回录像开始状态
  Future<Map<String, dynamic>> startRecord({
    required String streamId,
    int interval = 0,
  }) async {
    try {
      final queryParams = {
        'streamid': streamId, // 注意：接口要求的是streamid，不是streamId
        'interval': interval,
      };

      final response = await _baseService.get<Map<String, dynamic>>(
        '/cms/record/start',
        queryParameters: queryParams,
      );

      if (response.data != null) {
        final data = response.data!;
        if (data['code'] == 0 && data['success'] == true) {
          return data;
        } else {
          throw Exception(data['msg'] ?? '开始录像失败');
        }
      } else {
        throw Exception('开始录像响应数据为空');
      }
    } on DioException catch (e) {
      print('开始录像网络错误: ${e.message}');
      throw Exception('网络环境不佳，请稍后尝试');
    } catch (e) {
      print('开始录像错误: $e');
      throw Exception('网络环境不佳，请稍后尝试');
    }
  }

  /// 2.8.2 停止录像
  ///
  /// [streamId] 流ID (必填)
  ///
  /// 返回录像文件信息，包含文件总数、下载地址等
  Future<Map<String, dynamic>> stopRecord({required String streamId}) async {
    try {
      final queryParams = {
        'streamid': streamId, // 注意：接口要求的是streamid，不是streamId
      };

      final response = await _baseService.get<Map<String, dynamic>>(
        '/cms/record/stop',
        queryParameters: queryParams,
      );

      if (response.data != null) {
        final data = response.data!;
        if (data['code'] == 0 && data['success'] == true) {
          return data;
        } else {
          throw Exception(data['msg'] ?? '停止录像失败');
        }
      } else {
        throw Exception('停止录像响应数据为空');
      }
    } on DioException catch (e) {
      print('停止录像网络错误: ${e.message}');
      throw Exception('网络环境不佳，请稍后尝试');
    } catch (e) {
      print('停止录像错误: $e');
      throw Exception('网络环境不佳，请稍后尝试');
    }
  }

  /// 2.8.3 实时录像查询
  ///
  /// [streamId] 流ID (必填)
  ///
  /// 返回当前录像文件信息，包含文件总数、下载地址等
  Future<Map<String, dynamic>> queryRecord({required String streamId}) async {
    try {
      final queryParams = {
        'streamid': streamId, // 注意：接口要求的是streamid，不是streamId
      };

      final response = await _baseService.get<Map<String, dynamic>>(
        '/cms/record/query',
        queryParameters: queryParams,
      );

      if (response.data != null) {
        final data = response.data!;
        if (data['code'] == 0 && data['success'] == true) {
          return data;
        } else {
          throw Exception(data['msg'] ?? '查询录像失败');
        }
      } else {
        throw Exception('查询录像响应数据为空');
      }
    } on DioException catch (e) {
      print('查询录像网络错误: ${e.message}');
      throw Exception('网络环境不佳，请稍后尝试');
    } catch (e) {
      print('查询录像错误: $e');
      throw Exception('网络环境不佳，请稍后尝试');
    }
  }

  /// 2.8.4 设备抓图
  ///
  /// [serial] 设备编号 (必填)
  /// [channel] 通道序号，默认1
  /// [code] 通道编号，与channel二选一传递即可
  /// [timeout] 超时时间(秒)，默认15
  ///
  /// 返回image/jpeg格式图片数据
  Future<Map<String, dynamic>> snapshot({
    required String serial,
    int? channel,
    String? code,
    int timeout = 15,
  }) async {
    try {
      final queryParams = <String, dynamic>{
        'serial': serial,
        'timeout': timeout,
      };

      if (channel != null) {
        queryParams['channel'] = channel;
      }
      if (code != null && code.isNotEmpty) {
        queryParams['code'] = code;
      }

      final response = await _baseService.get<Map<String, dynamic>>(
        '/cms/control/snapshot',
        queryParameters: queryParams,
      );

      if (response.data != null) {
        final data = response.data!;
        if (data['code'] == 0 && data['success'] == true) {
          return data;
        } else {
          throw Exception(data['msg'] ?? '设备抓图失败');
        }
      } else {
        throw Exception('设备抓图响应数据为空');
      }
    } on DioException catch (e) {
      print('设备抓图网络错误: ${e.message}');
      throw Exception('网络环境不佳，请稍后尝试');
    } catch (e) {
      print('设备抓图错误: $e');
      throw Exception('网络环境不佳，请稍后尝试');
    }
  }

  // === 便捷方法 ===

  /// 开始流录像并返回是否成功
  ///
  /// [streamId] 流ID
  /// [segmentSeconds] 分段时间（秒），0表示不分段
  Future<bool> startStreamRecord(
    String streamId, {
    int segmentSeconds = 0,
  }) async {
    try {
      final response = await startRecord(
        streamId: streamId,
        interval: segmentSeconds,
      );
      return response['data'] == 'OK';
    } catch (e) {
      print('开始流录像失败: $e');
      return false;
    }
  }

  /// 停止流录像并返回录像文件列表
  ///
  /// [streamId] 流ID
  ///
  /// 返回录像文件列表，包含下载URL、开始时间、结束时间
  Future<List<Map<String, dynamic>>?> stopStreamRecord(String streamId) async {
    try {
      final response = await stopRecord(streamId: streamId);
      final recordList = response['data']?['RecordList'] as List?;
      return recordList?.cast<Map<String, dynamic>>();
    } catch (e) {
      print('停止流录像失败: $e');
      return null;
    }
  }

  /// 获取录像文件下载URL列表
  ///
  /// [streamId] 流ID
  ///
  /// 返回所有录像文件的下载URL
  Future<List<String>?> getRecordDownloadUrls(String streamId) async {
    try {
      final response = await queryRecord(streamId: streamId);
      final recordList = response['data']?['RecordList'] as List?;
      if (recordList != null) {
        return recordList
            .cast<Map<String, dynamic>>()
            .map((record) => record['DownloadURL']?.toString())
            .where((url) => url != null)
            .cast<String>()
            .toList();
      }
      return null;
    } catch (e) {
      print('获取录像下载URL失败: $e');
      return null;
    }
  }

  /// 获取录像文件总数
  ///
  /// [streamId] 流ID
  ///
  /// 返回录像文件总数
  Future<int?> getRecordCount(String streamId) async {
    try {
      final response = await queryRecord(streamId: streamId);
      return response['data']?['RecordCount'] as int?;
    } catch (e) {
      print('获取录像文件总数失败: $e');
      return null;
    }
  }

  /// 获取设备快照（抓图）
  ///
  /// [serial] 设备ID
  /// [channel] 通道号，默认1
  ///
  /// 返回是否成功获取快照
  Future<bool> takeSnapshot(String serial, {int channel = 1}) async {
    try {
      await snapshot(serial: serial, channel: channel);
      return true;
    } catch (e) {
      print('获取设备快照失败: $e');
      return false;
    }
  }

  /// 录像会话管理：开始录像 -> 等待 -> 停止录像
  ///
  /// [streamId] 流ID
  /// [durationSeconds] 录像时长（秒）
  /// [segmentSeconds] 分段时间（秒），0表示不分段
  ///
  /// 返回录像文件列表
  Future<List<Map<String, dynamic>>?> recordSession({
    required String streamId,
    required int durationSeconds,
    int segmentSeconds = 0,
  }) async {
    try {
      // 1. 开始录像
      final startSuccess = await startStreamRecord(
        streamId,
        segmentSeconds: segmentSeconds,
      );
      if (!startSuccess) {
        throw Exception('开始录像失败');
      }

      print('录像已开始，将录制 $durationSeconds 秒...');

      // 2. 等待指定时间
      await Future.delayed(Duration(seconds: durationSeconds));

      // 3. 停止录像并获取文件列表
      final recordFiles = await stopStreamRecord(streamId);

      if (recordFiles != null && recordFiles.isNotEmpty) {
        print('录像完成，共生成 ${recordFiles.length} 个文件');
        return recordFiles;
      } else {
        print('录像完成，但未获取到文件信息');
        return null;
      }
    } catch (e) {
      print('录像会话失败: $e');
      // 尝试停止录像以清理资源
      try {
        await stopRecord(streamId: streamId);
      } catch (_) {
        // 忽略停止录像的错误
      }
      return null;
    }
  }
}
